package org.example.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageInfo;
import org.example.config.R;
import org.example.domain.Role;
import org.example.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("role")
public class RoleController {
    @Autowired
    RoleService roleService;

    @RequestMapping("list")
    public PageInfo<Role> list(@RequestBody Role role, Page page){
        return roleService.list(role,page);
    }

    @RequestMapping("del")
    public R del(Integer id){
        roleService.del(id);
        return  R.successed(null);
    }

    @RequestMapping("update")
    public R update(@RequestBody Role role){
        roleService.update(role);
        return R.successed(null);
    }

    @RequestMapping("add")
    public R add(@RequestBody Role role){
        roleService.add(role);
        return R.successed(null);
    }

    @RequestMapping("daochu")
    public void daochu(HttpServletResponse response) throws IOException {
        List<Role> list=roleService.lists();
        // 通过工具类创建writer
        ExcelWriter writer = ExcelUtil.getWriter(true);

//自定义标题别名
        writer.addHeaderAlias("role", "角色名称");
        writer.addHeaderAlias("username", "权限标识符");
        writer.addHeaderAlias("status", "状态");
        writer.addHeaderAlias("createTime", "创建时间");

// 默认的，未添加alias的属性也会写出，如果想只写出加了别名的字段，可以调用此方法排除之
        writer.setOnlyAlias(true);

        writer.write(list, true);

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition","attachment;filename=test.xlsx");
        ServletOutputStream out=response.getOutputStream();

        writer.flush(out, true);
        writer.close();
        IoUtil.close(out);
    }

    @RequestMapping("getById")
    public R getById(Integer id){
            Role role=roleService.getById(id);
            return R.successed(role);
    }

}
